<template>
  <div class="rule-container">
    <div class="create-container">
      <el-button type="primary" @click="addRules">增加停车计费规则</el-button>
      <el-button @click="handleExport">导出Excel</el-button>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table :data="ruleList" style="width: 100%">
        <el-table-column type="index" label="序号" />
        <el-table-column label="计费规则编号" prop="ruleNumber" />
        <el-table-column label="计费规则名称" prop="ruleName" />
        <el-table-column label="免费时长(分钟)" prop="freeDuration" />
        <el-table-column label="收费上线(元)" prop="chargeCeiling" />
        <el-table-column label="计费方式">
          <template #default="scope">
            <span>{{ chargeTypeMap(scope.row.chargeType) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="计费规则" prop="ruleNameView" />
        <el-table-column label="操作" fixed="right" width="120">
          <template #default="scope">
            <el-button size="mini" type="text" @click="eidtBtn(scope.row.id)">编辑</el-button>
            <el-button size="mini" type="text" @click="delBtn(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page-container">
      <el-pagination
        layout="total, prev, pager, next"
        :total="total"
        :page-size="params.pageSize"
        :current-page.sync="params.page"
        @current-change="handleCurrentChange"
      />
    </div>
    <el-dialog :visible="dialogVisible" width="680px" :title="title" @close="closeDialog">
      <!-- 表单接口 -->
      <div class="form-container">
        <el-form ref="addForm" :model="addForm" :rules="addFormRules" label-position="top">
          <el-form-item label="计费规则编号" prop="ruleNumber">
            <el-input v-model="addForm.ruleNumber" placeholder="请输入计费规则编号" />
          </el-form-item>
          <el-form-item label="计费规则名称" prop="ruleName">
            <el-input v-model="addForm.ruleName" placeholder="请输入计费规则名称" />
          </el-form-item>
          <el-form-item label="计费方式" prop="chargeType">
            <el-radio-group v-model="addForm.chargeType" size="small">
              <el-radio label="duration" border>时长收费</el-radio>
              <el-radio label="turn" border>按次收费</el-radio>
              <el-radio label="partition" border>分段收费</el-radio>
            </el-radio-group>
          </el-form-item>
          <div class="flex-container">
            <el-form-item label="免费时长" prop="freeDuration">
              <el-input v-model="addForm.freeDuration" placeholder="请输入免费时长" />
            </el-form-item>
            <el-form-item label="收费上限" prop="chargeCeiling">
              <el-input v-model="addForm.chargeCeiling" placeholder="请输入收费上限" />
            </el-form-item>
          </div>
          <el-form-item label="计费规则" prop="chargeRule">
            <div v-if="addForm.chargeType === 'duration'">
              每 <el-input v-model="addForm.durationTime" class="input-box" /> 分钟 <el-input
                v-model="addForm.durationPrice"
                class="input-box"
              /> 元
            </div>
            <div v-if="addForm.chargeType === 'turn'">
              每次 <el-input v-model="addForm.turnPrice" class="input-box" /> 元
            </div>
            <div v-if="addForm.chargeType === 'partition'">
              <div class="item">
                <el-input v-model="addForm.partitionFrameTime" class="input-box" /> 小时内,每小时收费 <el-input
                  v-model="addForm.partitionFramePrice"
                  class="input-box"
                /> 元
              </div>
              <div class="item">
                每增加 <el-input v-model="addForm.partitionIncreaseTime" class="input-box" /> 小时,增加 <el-input
                  v-model="addForm.partitionIncreasePrice"
                  class="input-box"
                /> 元
              </div>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button size="mini" @click="closeDialog">取 消</el-button>
        <el-button size="mini" type="primary" @click="confirmBtn">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { addRules, delRules, editRules, getRules, getRulesDetail } from '@/api/rule'
import { utils, writeFile } from 'xlsx'
export default {
  name: 'Building',
  data() {
    return {
      ruleList: [],
      params: {
        page: 1,
        pageSize: 10
      },
      currentId: null,
      total: 0,
      dialogVisible: false, // 控制弹框关闭打开
      addForm: {
        ruleNumber: '', // 计费规则编号
        ruleName: '', // 计费规则名称
        chargeType: 'duration', // 计费规则类型 duration / turn / partition
        chargeCeiling: null,
        freeDuration: null,
        // 时长计费独有字段
        durationTime: null, // 时长计费单位时间
        durationPrice: null, // 时长计费单位价格
        durationType: 'hour',
        // 按次收费独有字段
        turnPrice: null,
        // 分段计费独有字段
        partitionFrameTime: null, // 段内时间
        partitionFramePrice: null, // 段内费用
        partitionIncreaseTime: null, // 超出时间
        partitionIncreasePrice: null // 超出费为收费价钱

      }, // 计费规则表单对象
      addFormRules: {
        ruleNumber: [
          {
            required: true,
            message: '请输入规则编号',
            trigger: 'blur'
          }
        ],
        ruleName: [
          {
            required: true,
            message: '请输入规则名称',
            trigger: 'blur'
          }
        ],
        chargeType: [
          {
            required: true,
            message: '请选择收费类型',
            trigger: 'blur'
          }
        ]
      } // 计费规则校验规则对象
    }
  },
  computed: {
    title() {
      return this.currentId ? '编辑计费规则' : '新增计费规则'
    }
  },
  created() {
    // 获取列表数据
    this.getRuleList()
  },
  methods: {
    // 获取列表数据
    async getRuleList() {
      const { data: { rows, total }} = await getRules(this.params)
      this.ruleList = rows
      this.total = total
    },
    // 分页功能
    handleCurrentChange(value) {
      this.params.page = value
      this.getRuleList()
    },

    chargeTypeMap(value) {
      const map = {
        // 时长收费:duration,按次收费:turn,分段收费:partition
        duration: '时长收费',
        turn: '按次收费',
        partition: '分段收费'
      }
      return map[value]
    },
    // 导出Excel
    async handleExport() {
      // 获取全部数据（根据实际接口调整）
      const { data: { rows }} = await getRules({
        page: 1,
        pageSize: 10000 // 假设最大数据量
      })

      // 数据转换
      const jsonData = rows.map(item => {
        item.chargeType = this.chargeTypeMap(item.chargeType)
        return {
          计费规则编号: item.ruleNumber,
          计费规则名称: item.ruleName,
          免费时长: item.freeDuration,
          收费上限: item.chargeCeiling,
          计费方式: item.chargeType,
          计费规则: item.ruleNameView
        }
      })
      // 创建工作簿
      const workbook = utils.book_new()
      const worksheet = utils.json_to_sheet(jsonData)

      // 设置列宽
      worksheet['!cols'] = [
        { wch: 15 }, { wch: 20 },
        { wch: 12 }, { wch: 12 },
        { wch: 15 }, { wch: 40 }
      ]

      // 添加工作表
      utils.book_append_sheet(workbook, worksheet, '计费规则')

      // 生成文件并下载
      writeFile(workbook, `计费规则_${new Date().toLocaleDateString()}.xlsx`)
    },
    // 新增规则
    addRules() {
      this.dialogVisible = true
    },
    // 编辑规则
    async eidtBtn(id) {
      this.dialogVisible = true
      this.currentId = id
      const { data } = await getRulesDetail(id)
      this.addForm = data
    },
    // 关闭弹窗
    closeDialog() {
      // 清除校验
      this.$refs.addForm.resetFields()
      this.dialogVisible = false
      this.currentId = null
    },
    // 确定按钮
    async confirmBtn() {
      await this.$refs.addForm.validate()
      if (!this.currentId) {
        await addRules(this.addForm)
      } else {
        await editRules(this.addForm)
      }
      this.closeDialog()
      this.getRuleList()
    },
    // 删除
    async delBtn(id) {
      this.$confirm('确认删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await delRules(id)
        this.getRuleList()
        // this.$message({
        //   type: 'success',
        //   message: '删除成功!'
        // })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }

  }
}
</script>

<style lang="scss" scoped>
.rule-container {
  padding: 20px;
  background-color: #fff;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}

.create-container {
  margin: 10px 0px;
}

.page-container {
  padding: 4px 0px;
  text-align: right;
}

.form-container {
  padding: 0px 140px;
}

.form-container {
  padding: 20px;
}

.flex-container {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.input-box {
  width: 100px;
  margin-right: 10px;
}

.item {
  margin-bottom: 10px;
}
</style>
